
#include "LoggerSettings.h"
#include "Common/Strings.h"

using namespace ttg::strings;
using namespace ttg::services;
using namespace ttg_internal::services;

//----------------------
//--- LoggerSettings ---
//----------------------

LoggerSettings::LoggerSettings()
	:ServiceSettings("Logger")
{
	set(All, Ignore);
	set(Errors, ShowMessageBox);
	set(UserMessages, PrintToFile);
}

std::string LoggerSettings::serialize()
{
	return getStringName() + "(log=" + logfile + "," +
							 "errors=" + toString(actions[Errors]) + "," +
							 "user=" + toString(actions[UserMessages]) + "," +
							 "ttgLib=" + toString(actions[ttgLibMessages]) + ")";
}

LoggerSettings LoggerSettings::deSerialize(const char *value)
{
	LoggerSettings res;
	StringSplitter sp_g;
	sp_g.setSplitter(',', false);
	sp_g.setString(value);
	for (size_t i = 0; i < sp_g.getCount(); i++)
	{
		StringSplitter sp_l;
		sp_l.setSplitter('=', false);
		sp_l.setString(sp_g[i]);
		if (sp_l.getCount() == 2)
		{
			try
			{
				if (sp_l[0] == std::string("log"))
					res.logfile = sp_l[1]; else
				if (sp_l[0] == std::string("errors"))
					res.actions[Errors] = (OnMessageAction)toInt32(sp_l[1]); else
				if (sp_l[0] == std::string("user"))
					res.actions[UserMessages] = (OnMessageAction)toInt32(sp_l[1]); else
				if (sp_l[0] == std::string("ttgLib"))
					res.actions[ttgLibMessages] = (OnMessageAction)toInt32(sp_l[1]);
			}
			catch (ttg::Error &) { }
		}
	}
	return res;
}

void LoggerSettings::enable()
{
	setEnabled(true);
}

void LoggerSettings::enable(const char *filename)
{
	logfile = filename;
	setEnabled(true);
}

void LoggerSettings::disable()
{
	setEnabled(false);
}

void LoggerSettings::set(MessageFilter filter, OnMessageAction action)
{
	if (filter == All)
		for (size_t i = 0; i < 3; i++)
			actions[i] = action;
	else
		actions[filter] = action;
}
